package com.zuihai.app.mvp.presenter;

import android.app.Application;
import android.content.Context;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.WindowManager;

import com.blankj.utilcode.util.LogUtils;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.RxUtils;
import com.zuihai.app.mvp.constant.MyConstant;
import com.zuihai.app.mvp.contract.FindRecyclerContract;
import com.zuihai.app.mvp.model.entity.BaseJson;
import com.zuihai.app.mvp.model.entity.FindItem;
import com.zuihai.app.mvp.ui.adapter.FindHomeRecyclerAdapter;
import com.zuihai.app.mvp.ui.adapter.FindRecyclerAdapter;
import com.zuihai.app.mvp.ui.utils.AccountHelper;
import com.zuihai.app.mvp.ui.utils.UserDataUtils;

import java.net.ConnectException;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import me.jessyan.rxerrorhandler.handler.RetryWithDelay;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/5/4 0004.
 */

@FragmentScope
public class FindRecyclerPresenter extends BasePresenter<FindRecyclerContract.Model, FindRecyclerContract.View> implements FindRecyclerContract.Presenter {
    private RxErrorHandler mErrorHandler;
    private Application mApplication;
    private AppManager mAppManager;
    private List<FindItem> mDatas = new ArrayList<>();
    private final FindRecyclerAdapter mAdapter;
    private FindHomeRecyclerAdapter mFHAdapter;
    private int mPageIndex = 1;

    @Inject
    public FindRecyclerPresenter(FindRecyclerContract.Model model, FindRecyclerContract.View rootView
            , RxErrorHandler handler, Application application, AppManager appManager) {
        super(model, rootView);
        this.mErrorHandler = handler;
        this.mApplication = application;
        this.mAppManager = appManager;
        WindowManager wm = (WindowManager) application
                .getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 14+14+4+4, mApplication.getResources().getDisplayMetrics());

        mFHAdapter=new FindHomeRecyclerAdapter(mDatas,width-padding,application);
        mAdapter = new FindRecyclerAdapter(mDatas,width-padding,application);

        mRootView.bindAdapter(mAdapter);
        mRootView.bindFHAdapter(mFHAdapter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mApplication = null;
    }

    @Override
    public void requestGoods(boolean isRefresh) {
        if (isRefresh) mPageIndex = 1;//如果是刷新获取第一页数据
        String uid = AccountHelper.getInstance().getUid();
        mModel.requestGoods(uid, mPageIndex)
                .compose(applySchedulers(isRefresh))
                .subscribe(getSubscriber(isRefresh));
    }

    //请求首页的推荐
    public void requestHomeRecommend(boolean isRefresh) {
        if (isRefresh) mPageIndex = 1;//如果是刷新获取第一页数据
        String uid = AccountHelper.getInstance().getUid();
        mModel.requestHomeRecommend(mPageIndex,uid )
                .compose(applySchedulers(isRefresh))
                .subscribe(getHomeSubscriber(isRefresh));
    }

    @Override
    public void requestService(boolean isRefresh) {
        if (isRefresh) mPageIndex = 1;//如果是刷新获取第一页数据
        String uid = AccountHelper.getInstance().getUid();
        mModel.requestService(uid, mPageIndex)
                .compose(applySchedulers(isRefresh))
                .subscribe(getSubscriber(isRefresh));
    }

    public void requestFindRecomment(boolean isRefresh) {
        if (isRefresh) mPageIndex = 1;//如果是刷新获取第一页数据
        String uid = AccountHelper.getInstance().getUid();
        mModel.requestFindRecomment( mPageIndex,uid)
                .compose(applySchedulers(isRefresh))
                .subscribe(getSubscriber(isRefresh));
    }
    @Override
    public void requestSecret(boolean isRefresh) {
        if (isRefresh) mPageIndex = 1;//如果是刷新获取第一页数据
        String uid = AccountHelper.getInstance().getUid();
        mModel.requestSecret(uid, mPageIndex)
                .compose(applySchedulers(isRefresh))
                .subscribe(getSubscriber(isRefresh));
    }

    @Override
    public void requestWhither(boolean isRefresh) {
        if (isRefresh) mPageIndex = 1;//如果是刷新获取第一页数据
        String uid = AccountHelper.getInstance().getUid();
        mModel.requestWhither(uid, mPageIndex)
                .compose(applySchedulers(isRefresh))
                .subscribe(getSubscriber(isRefresh));
    }




    public void requestMyFindSecret(boolean isRefresh) {
        if (isRefresh) mPageIndex = 1;//如果是刷新获取第一页数据

        String uid = AccountHelper.getInstance().getUid();
        String userID;
        if (TextUtils.isEmpty( MyConstant.HOMEPAGE_USERID)){
            userID=uid;
        }else {
            userID=MyConstant.HOMEPAGE_USERID;
        }
        mModel.requestMyFindSecret(userID, UserDataUtils.getInstance().userID(), mPageIndex)
                .compose(applySchedulers(isRefresh))
                .subscribe(getSubscriber(isRefresh));
    }

    public void requestMyCommodity(boolean isRefresh) {
        if (isRefresh) mPageIndex = 1;//如果是刷新获取第一页数据

        String uid = AccountHelper.getInstance().getUid();
        String userID;
        if (TextUtils.isEmpty( MyConstant.HOMEPAGE_USERID)){
            userID=uid;
        }else {
            userID=MyConstant.HOMEPAGE_USERID;
        }
        LogUtils.e("userID : "+userID);
        mModel.requestMyCommodity(userID, UserDataUtils.getInstance().userID(), mPageIndex)
                .compose(applySchedulers(isRefresh))
                .subscribe(getSubscriber(isRefresh));
    }


    public <T> Observable.Transformer<BaseJson<T>, List<T>> applySchedulers(boolean isRefresh) {
        return observable -> observable
                .retryWhen(new RetryWithDelay(3, 3))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(baseJson -> {
                    if (baseJson.isSuccess()) {
                        return baseJson.data.result;
                    }
                    return null;
                })
                .doAfterTerminate(new Action0() {
                    @Override
                    public void call() {
                        if (isRefresh) {
                            mRootView.hideLoading();
                        }
                    }
                })
                .compose(RxUtils.bindToLifecycle(mRootView));
    }

    @NonNull
    private ErrorHandleSubscriber<List<FindItem>> getSubscriber(final boolean isRefresh) {
        return new ErrorHandleSubscriber<List<FindItem>>(mErrorHandler) {
            @Override
            public void onNext(List<FindItem> items) {
                mPageIndex ++;//页角递增
                if (isRefresh) {
                    mAdapter.setNewData(items);
                    mRootView.hideLoading();
                } else {
                    if (items.isEmpty()){
                        mAdapter.loadMoreEnd();
                    }else{
                        mAdapter.addData(items);
                        mAdapter.loadMoreComplete();
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                if (!isRefresh) {
                    mAdapter.loadMoreFail();
                } else {
                    mRootView.hideLoading();
                    if (e instanceof ConnectException) {
                        mRootView.showMessage("网络连接失败");
                    } else {
                        mRootView.showMessage("好像断网");
                    }
                }
                mRootView.handleError(e);
            }
        };
    }

    @NonNull
    private ErrorHandleSubscriber<List<FindItem>> getHomeSubscriber(final boolean isRefresh) {
        return new ErrorHandleSubscriber<List<FindItem>>(mErrorHandler) {
            @Override
            public void onNext(List<FindItem> items) {
                mPageIndex ++;//页角递增
                if (isRefresh) {
                    mFHAdapter.setNewData(items);
                    mRootView.hideLoading();
                } else {
                    if (items.isEmpty()){
                        mFHAdapter.loadMoreEnd();
                    }else{
                        mFHAdapter.addData(items);
                        mFHAdapter.loadMoreComplete();
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                if (!isRefresh) {
                    mAdapter.loadMoreFail();
                } else {
                    mRootView.hideLoading();
                    if (e instanceof ConnectException) {
                        mRootView.showMessage("网络连接失败");
                    } else {
                        mRootView.showMessage("好像断网");
                    }
                }
                mRootView.handleError(e);
            }
        };
    }



}